/*
#include <mqtt.h>
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2015-07-29     Arda.Fu      first implementation
 */
#include <stdint.h>
#include <rtthread.h>
#include <rtdevice.h>

#include "led.h"
#include "key.h"
#include "sensors.h"
#include "wifi.h"
#include "mqtt.h"
#include "sound.h"

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

typedef int (*init_func)(void *arg);

typedef struct _init_object_t {
    const char *    name;
    init_func       func;
    void *          arg;
    rt_sem_t        sem;
} init_object_t;

typedef struct _main_sem_obj_t
{
    rt_sem_t    wifi_status_sem;
    rt_sem_t    alert_led_sem;
    rt_sem_t    alert_sound_sem;
    rt_sem_t    sensors_sem;
    rt_sem_t    key_sem;
    rt_sem_t    mqtt_sem;
} main_sem_obj_t;

#define DEFINE_A_INIT_OBJ(func, arg) \
    {\
        (#func),\
        (func),\
        (arg),\
        (RT_NULL),\
    }

/* add your init object here */
static init_object_t g_init_obj_table[] =
{
    DEFINE_A_INIT_OBJ(alert_led_init,   RT_NULL),
    DEFINE_A_INIT_OBJ(alert_sound_init, RT_NULL),
    DEFINE_A_INIT_OBJ(key_init,         RT_NULL),
    DEFINE_A_INIT_OBJ(sensors_init,     RT_NULL),
    DEFINE_A_INIT_OBJ(wifi_init,        RT_NULL),
    DEFINE_A_INIT_OBJ(mqtt_init,        RT_NULL),
};

int main(void)
{
    int i;
    int ret;
    int cnt = ARRAY_SIZE(g_init_obj_table);

    for (i = 0; i < cnt; i++) {
        g_init_obj_table[i].sem = rt_sem_create(g_init_obj_table[i].name, 0, RT_IPC_FLAG_PRIO);
        ret = g_init_obj_table[i].func(g_init_obj_table[i].sem);
        LOG_D("[%-20s] init ... [%s]", g_init_obj_table[i].name, ret == RT_EOK ? " OK " : "FAIL");
    }

    rt_sem_take(g_init_obj_table[4].sem, RT_WAITING_FOREVER); // wait for wifi-sem
    rt_sem_release(g_init_obj_table[5].sem); // take to mqtt

    while (1) {
        rt_sem_take(g_init_obj_table[0].sem, RT_WAITING_FOREVER);
        rt_sem_release(g_init_obj_table[1].sem);
        rt_sem_release(g_init_obj_table[2].sem);
    }
}

